<template>
  <div class="ai-analysis-chart">
    <div class="flex justify-between items-center mb-4">
      <div>
        <h3 class="text-lg font-bold">AI 分析趋势</h3>
        <p class="text-sm text-gray-500">最近30天AI评估变化</p>
      </div>
      <div class="flex space-x-2">
        <button v-for="metric in metrics" 
                :key="metric.key"
                @click="toggleMetric(metric.key)"
                :class="[
                  'px-3 py-1 text-xs rounded-full',
                  selectedMetrics.includes(metric.key) 
                    ? `${metric.activeClass} text-white` 
                    : 'bg-gray-100 text-gray-600'
                ]">
          {{ metric.label }}
        </button>
      </div>
    </div>
    
    <div class="h-80">
      <VChart :option="chartOption" autoresize />
    </div>
    
    <div class="mt-4 grid grid-cols-2 md:grid-cols-4 gap-4">
      <div v-for="stat in aiStats" :key="stat.label" 
           class="p-3 rounded-lg" :class="stat.bgClass">
        <h4 class="text-sm font-medium mb-1" :class="stat.textClass">{{ stat.label }}</h4>
        <p class="text-2xl font-bold" :class="stat.valueClass">{{ stat.value }}</p>
        <div class="flex items-center mt-1">
          <span :class="stat.changeClass">
            {{ stat.change >= 0 ? '↑' : '↓' }} {{ Math.abs(stat.change) }}%
          </span>
          <span class="text-xs text-gray-500 ml-2">较上周</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { LineChart } from 'echarts/charts';
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  MarkLineComponent,
  MarkPointComponent
} from 'echarts/components';
import VChart from 'vue-echarts';

use([
  CanvasRenderer,
  LineChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  MarkLineComponent,
  MarkPointComponent
]);

const props = defineProps({
  symbol: {
    type: String,
    required: true
  }
});

// 定义指标
const metrics = ref([
  { key: 'technical', label: '技术面', color: '#3B82F6', activeClass: 'bg-blue-600' },
  { key: 'fundamental', label: '基本面', color: '#10B981', activeClass: 'bg-green-600' },
  { key: 'sentiment', label: '市场情绪', color: '#F59E0B', activeClass: 'bg-yellow-600' },
  { key: 'risk', label: '风险评估', color: '#EF4444', activeClass: 'bg-red-600' }
]);

const selectedMetrics = ref(['technical', 'fundamental']);

// 生成模拟数据
const generateData = () => {
  const dates = Array.from({ length: 30 }, (_, i) => {
    const date = new Date();
    date.setDate(date.getDate() - (29 - i));
    return date.toISOString().split('T')[0];
  });

  const baseValue = 70;
  const data = {};
  metrics.value.forEach(metric => {
    data[metric.key] = dates.map(() => {
      return baseValue + Math.random() * 30 - 15;
    });
  });

  return { dates, data };
};

const { dates, data } = generateData();

// 图表配置
const chartOption = computed(() => {
  return {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        let result = params[0].axisValue + '<br/>';
        params.forEach(param => {
          const metric = metrics.value.find(m => m.key === param.seriesName);
          result += `${metric.label}: ${param.value.toFixed(1)}<br/>`;
        });
        return result;
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dates,
      boundaryGap: false
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      splitLine: {
        lineStyle: {
          color: '#f0f0f0'
        }
      }
    },
    series: metrics.value
      .filter(metric => selectedMetrics.value.includes(metric.key))
      .map(metric => ({
        name: metric.key,
        type: 'line',
        data: data[metric.key],
        smooth: true,
        showSymbol: false,
        lineStyle: {
          color: metric.color,
          width: 2
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: metric.color + '40' // 40 is hex for 25% opacity
            }, {
              offset: 1,
              color: metric.color + '00' // 00 is hex for 0% opacity
            }]
          }
        }
      }))
  };
});

// AI统计数据
const aiStats = ref([
  {
    label: '综合评分',
    value: '78.5',
    change: 5.2,
    bgClass: 'bg-blue-50',
    textClass: 'text-blue-700',
    valueClass: 'text-blue-900',
    changeClass: 'text-green-600 text-sm'
  },
  {
    label: '预测准确率',
    value: '85%',
    change: 2.8,
    bgClass: 'bg-green-50',
    textClass: 'text-green-700',
    valueClass: 'text-green-900',
    changeClass: 'text-green-600 text-sm'
  },
  {
    label: '风险指数',
    value: '32.6',
    change: -4.5,
    bgClass: 'bg-yellow-50',
    textClass: 'text-yellow-700',
    valueClass: 'text-yellow-900',
    changeClass: 'text-green-600 text-sm'
  },
  {
    label: '市场情绪',
    value: '积极',
    change: 12.3,
    bgClass: 'bg-purple-50',
    textClass: 'text-purple-700',
    valueClass: 'text-purple-900',
    changeClass: 'text-green-600 text-sm'
  }
]);

// 切换指标显示
const toggleMetric = (key) => {
  const index = selectedMetrics.value.indexOf(key);
  if (index === -1) {
    selectedMetrics.value.push(key);
  } else {
    selectedMetrics.value.splice(index, 1);
  }
};

// 监听股票代码变化
watch(() => props.symbol, (newSymbol) => {
  // 这里应该调用API获取新的股票数据
  console.log('股票代码变更为:', newSymbol);
  // 模拟数据更新
  const { dates: newDates, data: newData } = generateData();
  Object.assign(data, newData);
});
</script>